//
//  SellRecodeDetailViewController.m
//  EasyToTesco2.0
//
//  Created by knew on 16/11/14.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "SellRecodeDetailViewController.h"
#import "SelevtedSellRecodeDetailView.h"
#import "SellRecordOrderStatusModel.h"
#import "LastSellRecodeTableViewCell.h"
#import "ShopDetailModel.h"
#import "LogInPassWordFooterView.h"

@interface SellRecodeDetailViewController ()<UITableViewDelegate,UITableViewDataSource,didClickSelectedSellRecodeDetailButtonDelegate,LogInPassWordFooterDelegate>

{
    MBProgressHUD *progressHUD;
    NSInteger _statusType;
    
    NSInteger _indexPage;
}

@property (nonatomic,strong)SelevtedSellRecodeDetailView *selectedView;

@property (nonatomic,strong)UITableView *sellTableView;

/**
 订单状态数组
 */
@property (nonatomic,strong)NSMutableArray *orderStatusArray;

/**
 收货人数组
 */
@property (nonatomic,strong)NSMutableArray *orderInfo;

/**
 订单状态字典
 */
@property (nonatomic,strong)NSDictionary *firstDictionary;

@property (nonatomic,strong)NSMutableArray *textFieldArray;

@property (nonatomic,strong)NSMutableArray *shopListArray;

@property (nonatomic,strong)NSMutableArray *shopInfoArray;
@end

@implementation SellRecodeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addSellRecodeSelectedView];
    [self addSellRecodeTableView];
    self.title = @"订单详情";
    [self loadOrderInfoData];
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    _statusType = 1000;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    
}


- (void)loadOrderInfoData {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary *params = @{
                                 @"dxh":self.orderNumber,
                                 @"username":USERNAME
                                 };
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/user/orderinfo" completeBlock:^(id object) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [progressHUD hide:YES];
            });
            NSLog(@"%@",object);
            
            if (JudgeBackDataCode) {
                self.firstDictionary = [object[@"data"] objectForKey:@"dd"];
                self.shopListArray = [object[@"data"] objectForKey:@"shangpin"];
    
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.sellTableView reloadData];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSDictionary *msg = [object objectForKey:@"message"];
                    MBProgressHUD *hud = [MBProgressHUD showMessage:[NSString stringWithFormat:@"%@",msg[@"view"]] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                    [self.view addSubview:hud];
                });
            }
        }];
        
    });
}

- (void)LogInPassWordFooterViewButton:(UIButton *)button {
    NSLog(@"%s",__func__);
    [self clearTextFieldArray];
    UITextField *kuaidi = self.textFieldArray.firstObject;
    UITextField *number = self.textFieldArray.lastObject;
    
    NSLog(@"%@%@",kuaidi.text,number.text);
    
    NSDictionary *params = @{
                             @"dxh":self.firstDictionary[@"dxh"],
                             @"username":USERNAME,
                             @"gongsi":kuaidi.text,
                             @"danhao":number.text
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/user/order_fahuo" completeBlock:^(id object) {
        
        [JudgeBackDataCodeMessage JudgeBackDataCodeMessage:@"订单操作成功" andObjece:object andAddHUDView:self.view andPopViewController:^(id object) {
//            for (UITextField *textField in self.textFieldArray) {
//                textField.enabled = NO;
//            }
        }];
    }];
    
}

- (void)didViewClickClearTextField {
    [self clearTextFieldArray];
}

- (void)addSellRecodeSelectedView {
    SelevtedSellRecodeDetailView * SelectedView = [[SelevtedSellRecodeDetailView alloc] initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT * 0.07)];
    SelectedView.delegate = self;
    self.selectedView = SelectedView;
    [self.view addSubview:SelectedView];
}

- (void)addSellRecodeTableView {
    CGFloat y = CGRectGetMaxY(self.selectedView.frame);
    //    NSLog(@"%f",y);
    self.sellTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, y, WIDTH, HEIGHT - y - HEIGHT * 0.07)style:UITableViewStylePlain];
    self.sellTableView.delegate = self;
    self.sellTableView.dataSource = self;
    self.sellTableView.backgroundColor = BACKGROUND_COLOR;
    self.sellTableView.tableFooterView = [[UIView alloc] init];
    self.sellTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.sellTableView.estimatedRowHeight = 44;
    [self.view addSubview:self.sellTableView];
}

- (void)didClickSelectedSellRecodeDetailButton:(UIButton *)button {
    NSLog(@"%ld",button.tag);
    
    if (button.tag == _statusType) return;
    _statusType = button.tag;
    if (button.tag == 1000) {
        [self loadOrderInfoData];
    } else {
        [self.sellTableView reloadData];
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_statusType == 1001) {
        return self.shopListArray.count;
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (_statusType == 1001) {
        if (section == 0) {
            return 0.01;
        } else {
            return 10;
        }
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (_statusType == 1003) {
        LogInPassWordFooterView *footerView = [[LogInPassWordFooterView alloc] initWithFrame:CGRectMake(0, 60, WIDTH, HEIGHT/5)];
        footerView.delegate = self;
        [footerView.button setTitle:@"确认发货" forState:UIControlStateNormal];
        return footerView;
        
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (_statusType == 1003) {
        return HEIGHT/5;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_statusType == 1000) {
        return 7;
    } else if (_statusType == 1001) {
        return 6;
    } else if (_statusType == 1002) {
        return 4;
    } else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_statusType == 1000) {
        
        UITableViewCell *status = [tableView dequeueReusableCellWithIdentifier:@"status"];
        
        if (!status) {
            status = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"status"];
            status.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        SellRecordOrderStatusModel *firstModel = self.orderStatusArray[indexPath.row];
        status.textLabel.text = [NSString stringWithFormat:@"%@%@",firstModel.left,self.firstDictionary[firstModel.right]];
        
        if (![NSString stringWithFormat:@"%@",self.firstDictionary[firstModel.right]].length) {
            status.textLabel.text = [NSString stringWithFormat:@"%@暂无数据",firstModel.left];
        }
        
        if ([firstModel.right isEqualToString:@"fid"]) {
            NSString *string;
            switch ([self.firstDictionary[firstModel.right] integerValue]) {
                case 1:
                    string = @"充值账户";
                    break;
                    
                default:
                    string = @"积分消费";
                    break;
            }
            status.textLabel.text = [NSString stringWithFormat:@"%@%@",firstModel.left,string];
        }
        
        if ([firstModel.right isEqualToString:@"kuaidi"]) {
            NSString *string;
            switch ([self.firstDictionary[firstModel.right] integerValue]) {
                case 1:
                    string = @"已发货";
                    break;
                    
                case 4:
                    string = @"已收货";
                    break;
                    
                default:
                    string = @"未发货";
                    break;
            }
            status.textLabel.text = [NSString stringWithFormat:@"%@%@",firstModel.left,string];
        }
        
        if (indexPath.row == 5 || indexPath.row == 6) {
            if (![NSString stringWithFormat:@"%@",self.firstDictionary[@"gongsi"]].length && ![NSString stringWithFormat:@"%@",self.firstDictionary[@"danhao"]].length) {
                NSString *string = @"(请在发货信息一栏中填写)";
                NSString *labelString = [NSString stringWithFormat:@"%@%@",firstModel.left,string];
                NSMutableAttributedString *textString = [[NSMutableAttributedString alloc] initWithString:labelString];
                NSInteger length;
                if (indexPath.row == 5) {
                    length = 5;
                } else {
                    length = 4;
                }
                [textString addAttribute:NSForegroundColorAttributeName value:DEFAULT_COLOR range:NSMakeRange(length, labelString.length - length)];
                status.textLabel.attributedText = textString;
            }
        }
        
        return status;
        
    } else if (_statusType == 1001) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"second"];
        
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"second"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        NSDictionary *diction = self.shopListArray[indexPath.section];
        SellRecordOrderStatusModel *statusModel = self.shopInfoArray[indexPath.row];
        NSString *string = statusModel.right;
        cell.textLabel.text = [NSString stringWithFormat:@"%@%@",statusModel.left,diction[string]];
        
        return cell;
        
    } else if (_statusType == 1002) {
        
        UITableViewCell *thired = [tableView dequeueReusableCellWithIdentifier:@"thired"];
        
        if (!thired) {
            thired = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"thired"];
            thired.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        SellRecordOrderStatusModel *model = self.orderInfo[indexPath.row];
        thired.textLabel.text = [NSString stringWithFormat:@"%@%@",model.left,self.firstDictionary[model.right]];
        
        if (indexPath.row == 3) {
            thired.textLabel.text = [NSString stringWithFormat:@"送货地址：%@%@%@%@",self.firstDictionary[@"s_province"],self.firstDictionary[@"s_city"],self.firstDictionary[@"s_county"],self.firstDictionary[@"dizhi"]];
            thired.textLabel.numberOfLines = 0;
        }
        
        return thired;
        
    } else {
        LastSellRecodeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"last"];
        
        if (!cell) {
            cell = [[LastSellRecodeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"last"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (indexPath.row == 0) {
            cell.leftLabel.text = @"快递公司：";
            if ([NSString stringWithFormat:@"%@",self.firstDictionary[@"gongsi"]].length) {
                cell.secondTextField.text = [NSString stringWithFormat:@"%@",self.firstDictionary[@"gongsi"]];
            } else {
                cell.secondTextField.enabled = YES;
            }
        } else {
            cell.leftLabel.text = @"运单编号：";
            if ([NSString stringWithFormat:@"%@",self.firstDictionary[@"danhao"]].length) {
                cell.secondTextField.text = [NSString stringWithFormat:@"%@",self.firstDictionary[@"danhao"]];
                cell.secondTextField.keyboardType = UIKeyboardTypeNumberPad;
            } else {
                cell.secondTextField.enabled = YES;
                cell.secondTextField.keyboardType = UIKeyboardTypeNumberPad;
            }
        }
        
        cell.secondTextField.tag = indexPath.row;
        [self.textFieldArray addObject:cell.secondTextField];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_statusType == 1003) {
        [self clearTextFieldArray];
    }
}

- (void)clearTextFieldArray {
    
    [UIView animateWithDuration:0.5 animations:^{
        for (UITextField *textField in self.textFieldArray) {
            [textField resignFirstResponder];
        }
    }];
}

- (NSMutableArray *)orderStatusArray {
    if (!_orderStatusArray) {
        
        NSString *path = [[NSBundle mainBundle]pathForResource:@"SellRecodeOrderState" ofType:@"plist"];
        NSArray *array = [NSMutableArray arrayWithContentsOfFile:path];
        _orderStatusArray = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            SellRecordOrderStatusModel *model = [[SellRecordOrderStatusModel alloc] initWithDictionary:dict error:0];
            if (model) {
                NSLog(@"%@",model);
                [_orderStatusArray addObject:model];
            }
        }
    }
    return _orderStatusArray;
}

- (NSDictionary *)firstDictionary {
    if (!_firstDictionary) {
        _firstDictionary = [NSDictionary dictionary];
    }
    return _firstDictionary;
}

- (NSMutableArray *)orderInfo {
    if(!_orderInfo) {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"Order" ofType:@"plist"];
        NSArray *array = [NSMutableArray arrayWithContentsOfFile:path];
        _orderInfo = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            SellRecordOrderStatusModel *model = [[SellRecordOrderStatusModel alloc] initWithDictionary:dict error:0];
            if (model) {
                [_orderInfo addObject:model];
            }
        }
    }
    return _orderInfo;
}

- (NSMutableArray *)shopInfoArray {
    if (!_shopInfoArray) {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"Detail" ofType:@"plist"];
        NSArray *array = [NSMutableArray arrayWithContentsOfFile:path];
        _shopInfoArray = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            SellRecordOrderStatusModel *model = [[SellRecordOrderStatusModel alloc] initWithDictionary:dict error:0];
            if (model) {
                [_shopInfoArray addObject:model];
            }
        }
    }
    return _shopInfoArray;
    
}

- (NSMutableArray *)textFieldArray {
    if (!_textFieldArray) {
        _textFieldArray = [NSMutableArray array];
    }
    return _textFieldArray;
}

- (NSMutableArray *)shopListArray {
    if (!_shopListArray) {
        _shopListArray = [NSMutableArray array];
    }
    return _shopListArray;
}

@end
